package com.hsogoo.study.concurrency;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 *
 * Created by za-huangsaigang on 2018/8/27.
 */
public class AtomicIntegerWithLockTest {

    @Test
    public void test() throws InterruptedException {

        final AtomicIntegerWithLock value =new AtomicIntegerWithLock(10);

        assertEquals(value.compareAndSet(5, 3), false);
        assertEquals(value.get(), 10);
        assertTrue(value.compareAndSet(10, 5));
        assertEquals(value.get(), 5);
        value.set(0);
        assertEquals(value.getAndIncrement(), 0);                   //i++
        assertEquals(value.incrementAndGet(), 2);                   //++i
        assertEquals(value.getAndAdd(2),2);
        assertEquals(value.addAndGet(2), 6);
        assertEquals(value.getAndSet(5), 6);
        assertEquals(value.get(), 5);

        /**
         * 所有get开头的是先返回再操作
         */

        //以下10个线程进行加操作
        final int threadSize = 10;
        Thread[] ts =new Thread[threadSize];
        for(int i=0; i< threadSize; i++){
            ts[i] = new Thread(){
                @Override
                public void run() {
                    value.incrementAndGet();
                }
            };
        }
        for(Thread t: ts){
            t.start();
        }
        for(Thread t: ts){
            t.join();
        }
        assertEquals(value.get(), 15);

    }




}
